import { getDicByCodeSort } from '@/components/common/PateoForm/utils/helper';
import { Button, Card, Col, DatePicker, Form, Input, message, Popconfirm, Row, Select } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import styles from './style.less';

const { Option } = Select;
const formItemLayout = {
  labelCol: {
    xs: { span: 0 },
    sm: { span: 0 },
  },
  wrapperCol: {
    xs: { span: 0 },
    sm: { span: 0 },
    md: { span: 0 },
  },
};

const fieldLabels = {
  projectId: '项目',
  deviceId: '设备编号',
  deviceName: '设备名称',
  versionHardware: '硬件版本号',
  versionSoftware: '软件版本号',
  batchNo: '批次号',
  deviceStatus: '设备状态',
  imei: 'IMEI',
  ssid: 'WIFI账号',
  pin: 'WIFI密码',
  enrollStatus: '激活状态',
  enrollDate: '激活时间',
  produceDate: '生产日期 ',
  dynamicSecretkey: '动态秘钥 ',
  deviceSkey: '蓝牙识别码',
  bluetoothMac: '蓝牙mac地址',
  bluetoothId: '蓝牙ID',
  locBluetoothIds: '定位蓝牙ID',
  bluetoothName: '蓝牙名称',
  atbType: 'atbType',
  aesKey: 'aesKey',
  eolDate: 'eolDate',
  productReference: 'productReference',
  apnFlag: 'apnFlag',
};

@connect(state => ({
  tbox1: state.tbox1,
}))
export default class TboxAdd extends PureComponent {
  formRef = React.createRef<FormInstance>();

  static contextTypes = {
    dicData: PropTypes.array,
  };
  state = {
    projectId: '',
    projectIdData: [],
    query: {},
    buttonLoading: false,
  };

  componentWillMount() {
    if (this.props.location && this.props.location.state) {
      this.setState({
        query: this.props.location.state.obj,
        projectId: this.props.location.state.data.projectId,
      });
    }
  }
  componentDidMount() {
    const { dispatch } = this.props;
    if (this.props.location.flag) {
      const record = this.props.location.state.data.data;
      this.formRef.current?.resetFields();
      this.formRef.current?.setFieldsValue({
        deviceId: record.deviceId,
        deviceName: record.deviceName,
        versionHardware: record.versionHardware,
        versionSoftware: record.versionSoftware,
        batchNo: record.batchNo,
        deviceStatus:
          record.deviceStatus == null ? record.deviceStatus : record.deviceStatus.toString(),
        imei: record.imei,
        ssid: record.ssid,
        pin: record.pin,
        enrollStatus:
          record.enrollStatus == null ? record.enrollStatus : record.enrollStatus.toString(),
        enrollDate: record.enrollDate ? moment(record.enrollDate) : record.enrollDate,
        produceDate: record.produceDate ? moment(record.produceDate) : record.produceDate,
        sid: this.props.location.state.data.sid,
        dynamicSecretkey: record.dynamicSecretkey,
        deviceSkey: record.deviceSkey,
        bluetoothMac: record.bluetoothMac,
        bluetoothId: record.bluetoothId,
        locBluetoothIds: record.locBluetoothIds,
        bluetoothName: record.bluetoothName,
        createDate: record.createDate,
        createBy: record.createBy,
        delFlag: record.delFlag,
        version: record.version,
        atbType: record.atbType,
        aesKey: record.aesKey,
        eolDate: record.eolDate ? moment(record.eolDate) : record.eolDate,
        productReference: record.productReference ? record.productReference : '',
        apnFlag: record.apnFlag,
      });
    } else {
      dispatch({
        type: 'basedata/fetchProject',
        callback: data => {
          this.setState({
            projectIdData: data,
          });
        },
      });
    }
  }

  canceladd = () => {
    this.props.form.resetFields();
  };

  goBack = () => {
    const { dispatch } = this.props;
    this.formRef.current?.resetFields();
    dispatch(routerRedux.push({ pathname: '/connectPlat/tbox' }));
  };

  canceledit = () => {
    const { query } = this.state;
    const { dispatch } = this.props;
    this.formRef.current?.resetFields();
    dispatch(routerRedux.push({ pathname: '/connectPlat/tbox', state: { query } }));
  };

  submitForm = () => {
    this.formRef.current?.submit();
  };

  ok = (values: any) => {
    const { dispatch } = this.props;
    const obj = values;
    if (values.eolDate) {
      obj.eolDate = values.eolDate.format('YYYY-MM-DD HH:mm:ss');
    }

    this.setState({
      buttonLoading: true,
    });
    const { query } = this.state;
    const type = 'tbox1/postObjWithRes';
    let url = values.sid ? '/tbox/edit' : '/tbox/add';
    dispatch({
      type: type,
      payload: { url: url, ...obj },
      callback: response => {
        if (response.statusCode === '0') {
          message.success('操作成功').then(() => {});
          this.setState({
            buttonLoading: false,
          });
          this.formRef.current?.resetFields();
          if (url === '/tbox/edit') {
            dispatch(routerRedux.push({ pathname: '/connectPlat/tbox', state: { query } }));
          } else {
            dispatch(routerRedux.push('/connectPlat/tbox'));
          }
        } else {
          this.formRef.current?.resetFields();
          this.setState({
            buttonLoading: false,
          });
        }
      },
    });
  };

  render() {
    const { buttonLoading } = this.state;
    const productReferenceOptions = getDicByCodeSort(this.context.dicData, 'productReference');
    const apnFlagOptions = getDicByCodeSort(this.context.dicData, 'apnFlag');
    console.log(this.props.location.flag);

    if (this.props.location.flag) {
      return (
        <PageHeaderLayout title="" wrapperClassName={styles.advancedForm}>
          <Card title="" className={styles.card} bordered={false}>
            <Form layout="vertical" hideRequiredMark ref={this.formRef} onFinish={this.ok}>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.deviceId}
                    name="deviceId"
                    rules={[{ required: true, message: '请输入T-box设备ID' }]}
                  >
                    <Input placeholder="请输入T-box设备ID" disabled maxLength={20} />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.deviceName}
                    name="deviceName"
                    rules={[{ required: true, message: '设备名称' }]}
                  >
                    <Input placeholder="设备名称" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.deviceStatus}
                    name="deviceStatus"
                    rules={[{ required: false, message: '设备状态' }]}
                  >
                    <Select
                      placeholder="请设置设备状态"
                      allowClear
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                    >
                      <Option value="0">出厂</Option>
                      <Option value="1">销售</Option>
                      <Option value="2">激活</Option>
                      <Option value="3">替换</Option>
                      <Option value="4">报废</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.versionHardware}
                    name="versionHardware"
                    // rules={[{ required: false, message: '硬件版本号长度不能超过100', pattern: /^.{1,100}$/ }]}
                  >
                    <Input placeholder="请输入硬件版本号" maxLength={100} />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.versionSoftware}
                    name="versionSoftware"
                    // rules={[{required: false, message: '软件版本号长度不能超过100', pattern: /^.{1,100}$/ }]}
                  >
                    <Input placeholder="请输入软件版本号" maxLength={100} />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.batchNo}
                    name="batchNo"
                    rules={[{ required: false, message: '设备批次号' }]}
                  >
                    <Input placeholder="请输入批次号" maxLength={100} />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.imei}
                    name="imei"
                    rules={[
                      { required: false, message: 'IMEI编号长度不能超过20', pattern: /^\w{1,20}$/ },
                    ]}
                  >
                    <Input placeholder="请输入IMEI编号" maxLength="20" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <Form.Item {...formItemLayout} label={fieldLabels.ssid} name="ssid">
                    <Input placeholder="请输入WIFI账号" maxLength="20" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <Form.Item {...formItemLayout} label={fieldLabels.pin} name="pin">
                    <Input placeholder="请输入WIFI密码" maxLength="20" />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <Form.Item {...formItemLayout} label={fieldLabels.produceDate} name="produceDate">
                    <DatePicker
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      placeholder="生产日期"
                      disabled
                    />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.enrollStatus}
                    name="enrollStatus"
                    rules={[{ required: false, message: '激活状态' }]}
                  >
                    <Select
                      placeholder="请设置激活状态"
                      allowClear
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                    >
                      <Option value="1">成功</Option>
                      <Option value="2">失败</Option>
                      <Option value="3">进行中</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.enrollDate}
                    name="enrollDate"
                    rules={[{ required: false, message: '激活时间' }]}
                  >
                    <DatePicker
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      placeholder="激活时间"
                      disabled
                    />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.locBluetoothIds}
                    name="locBluetoothIds"
                    rules={[{ required: false, message: '定位蓝牙ID,多个请用逗号分开' }]}
                  >
                    <Input placeholder="定位蓝牙ID,多个请用逗号分开" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.dynamicSecretkey}
                    name="dynamicSecretkey"
                    rules={[{ required: false, message: '动态秘钥' }]}
                  >
                    <Input maxLength={50} placeholder="请输入动态秘钥" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.deviceSkey}
                    name="deviceSkey"
                    rules={[{ required: false, message: '蓝牙识别码' }]}
                  >
                    <Input placeholder="请设置蓝牙识别码" />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.bluetoothMac}
                    name="bluetoothMac"
                    rules={[{ required: false, message: '蓝牙mac地址' }]}
                  >
                    <Input placeholder="请输入蓝牙mac地址" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.bluetoothId}
                    name="bluetoothId"
                    rules={[{ required: false, message: '蓝牙ID' }]}
                  >
                    <Input placeholder="请输入蓝牙ID" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.bluetoothName}
                    name="bluetoothName"
                    rules={[{ required: false, message: '蓝牙名称' }]}
                  >
                    <Input placeholder="请设置蓝牙名称" />
                  </Form.Item>
                </Col>
              </Row>
              {this.state.projectId === 'baic53' ? null : (
                <div>
                  <Row gutter={16}>
                    <Col lg={6} md={12} sm={24}>
                      <Form.Item
                        {...formItemLayout}
                        label={fieldLabels.eolDate}
                        name="eolDate"
                        rules={[{ required: false, message: 'eolDate' }]}
                      >
                        <DatePicker
                          showTime
                          format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请设置eolDate"
                        />
                      </Form.Item>
                    </Col>
                    <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                      <Form.Item
                        {...formItemLayout}
                        label={fieldLabels.aesKey}
                        name="aesKey"
                        rules={[{ required: false, message: 'aesKey' }]}
                      >
                        <Input placeholder="请输入aesKey" />
                      </Form.Item>
                    </Col>
                    <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                      <Form.Item
                        {...formItemLayout}
                        label={fieldLabels.atbType}
                        name="atbType"
                        rules={[{ required: false, message: 'atbType' }]}
                      >
                        <Input placeholder="请设置atbType" />
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col lg={6} md={12} sm={24}>
                      <Form.Item
                        {...formItemLayout}
                        label={fieldLabels.productReference}
                        name="productReference"
                        rules={[{ required: false, message: 'productReference' }]}
                      >
                        <Select
                          placeholder="请选择productReference"
                          allowClear
                          getPopupContainer={triggerNode => triggerNode.parentNode}
                        >
                          <Option value="">高级T</Option>
                          {productReferenceOptions}
                        </Select>
                      </Form.Item>
                    </Col>
                    <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                      <Form.Item
                        {...formItemLayout}
                        label={fieldLabels.apnFlag}
                        name="apnFlag"
                        rules={[{ required: false, message: 'apnFlag' }]}
                      >
                        <Select
                          placeholder="请选择apnFlag"
                          allowClear
                          getPopupContainer={triggerNode => triggerNode.parentNode}
                        >
                          {apnFlagOptions}
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>
                </div>
              )}
              <Row>
                <Col>
                  <Form.Item {...formItemLayout} label="" style={{ display: 'none' }} name="sid">
                    <Input />
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label=""
                    style={{ display: 'none' }}
                    name="createDate"
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label=""
                    style={{ display: 'none' }}
                    name="createBy"
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label=""
                    style={{ display: 'none' }}
                    name="version"
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label=""
                    style={{ display: 'none' }}
                    name="delFlag"
                  >
                    <Input />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
            <Form layout="vertical" hideRequiredMark>
              <Row gutter={16}>
                <Col xl={{ span: 5, offset: 9 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <div>
                    <Button
                      loading={buttonLoading}
                      key="submit"
                      type="primary"
                      size="default"
                      // onClick={validate}
                      onClick={this.submitForm}
                    >
                      提交
                    </Button>
                    &nbsp;&nbsp;
                    <Popconfirm title="确定放弃该T-BOX修改吗?" onConfirm={() => this.canceledit()}>
                      <Button key="back" size="default">
                        取消
                      </Button>
                    </Popconfirm>
                  </div>
                </Col>
              </Row>
            </Form>
          </Card>
        </PageHeaderLayout>
      );
    } else {
      return (
        <PageHeaderLayout title="">
          <div align="center" width="100%" height="100%">
            <h2>未选择任何TBOX,请返回列表选择</h2>
            <a onClick={this.goBack}>返回</a>
          </div>
        </PageHeaderLayout>
      );
    }
  }
}
